//
//  XLCameraRecordTool.m
//  industry
//
//  Created by xl on 2020/12/14.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "XLCameraRecordTool.h"
#import <CoreServices/CoreServices.h>
#import <Photos/Photos.h>

@interface XLCameraRecordTool ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *imagePickerVC;

@property (nonatomic, copy) XLCameraRecordBlock recordBlock;
@property (nonatomic, strong) UIViewController *currentVC;

@end

@implementation XLCameraRecordTool

XLShareInstance_implementation(XLCameraRecordTool)

- (void)startCameraRecordViewController:(UIViewController *)controller
                          completeBlock:(XLCameraRecordBlock)completeBlock; {
    self.currentVC = controller;
    self.recordBlock = completeBlock;
    [self.imagePickerVC setMediaTypes:@[(NSString *)kUTTypeMovie]];
    _imagePickerVC.delegate = self;
    // 设置录制视频的质量
    [_imagePickerVC setVideoQuality:UIImagePickerControllerQualityTypeHigh];
    //设置最长摄像时间
    [_imagePickerVC setVideoMaximumDuration:300];
    [_imagePickerVC setAllowsEditing:NO];
    
    [controller presentViewController:_imagePickerVC animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {

    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    // 判断获取类型：图片
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]){
        UIImage *image =  [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *data = UIImageJPEGRepresentation(image, 1);
        self.recordBlock(data);
        
    }else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
        // 判断获取类型：视频
        //获取视频文件的url
        NSURL* mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
        self.recordBlock(mediaURL);
    }
    [picker  dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    self.recordBlock(nil);
    [picker  dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Setter/getter
- (UIImagePickerController *)imagePickerVC {
    if (!_imagePickerVC) {
        _imagePickerVC = [[UIImagePickerController alloc] init];
        [_imagePickerVC setSourceType:UIImagePickerControllerSourceTypeCamera];
    }
    return _imagePickerVC;
}

@end
